import type { Module } from "vuex";
import type { RootState } from "../types";
import request from "@/public/request";


interface message {
    readonly id: number,
    msgTitle: string,
    msgDescription: string,
    time: Date,
    isRead: boolean
}

export interface unReadMessage {
    message: Array<message>,
    unReadCount: number
}

const module: Module<unReadMessage, RootState> = {
    namespaced: true,
    state: {
        message: [],
        unReadCount: 0
    },
    mutations: {
        /**
         * 设置未读消息
         * @param state 
         * @param data
         */
        setMessage(state, data) {
            state.message = data;
        },
        /**
         * 设置未读消息总数
         * @param state 
         * @param data
         */
        setUnReadCount(state, data) {
            state.unReadCount = data;
        },
        addUnReadMessage(state, data) {
            state.message.push(data)
            state.unReadCount++
        }
    },
    actions: {
        /**
         * 获得未读消息数据
         * @param 
         */
        getUnReadMessageData({ commit, state }) {
            request.get(
                "/api/noticesend/query", {
                PageIndex: 1,
                PageSize: 50,
                ReadFlag: 'N',
            }
            ).then(res => {
                let messages = res.content.map((item: any) => {
                    return {
                        id: item.id,
                        msgTitle: item.title,
                        msgDescription: "",
                        time: item.sendTime,
                        isRead: item.readFlag == "Y"
                    }
                });
                let unReadCount = res.totalElements

                commit('setMessage', messages)
                commit('setUnReadCount', unReadCount)
            });
        },
        updateUnReadMessage({ commit }, data) {
            commit('setMessage', data.messages)
            commit('setUnReadCount', data.unReadCount)
        },
        addUnReadMessage({ commit }, data) {
            let message = {
                id: data.id,
                msgTitle: data.title,
                msgDescription: "",
                time: data.sendTime,
                isRead: data.readFlag == "Y"
            }
            commit('addUnReadMessage', message)
        },
        readMessage({ dispatch, commit, state }, data) {
            let readIndex = state.message.findIndex(item => {
                return item.id == data.id
            })
            let message = state.message
            if (readIndex != -1) {
                // message[readIndex].isRead = true
                // commit('setMessage', message)
                // commit('setUnReadCount', --state.unReadCount)
                dispatch("getUnReadMessageData");
            }

        }
    },
};

export default module;
